package com.qiaofang.collectmanage.facade.globalexception.handler;


import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.util.StringUtil;
import com.qiaofang.collectmanage.stub.constants.CollectManageResponseCode;


/**
 * 全局异常处理器
 * @author Administrator
 *
 */
@ControllerAdvice(basePackages="com.qiaofang.collectmanage")
public class CollectManageGlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(CollectManageGlobalExceptionHandler.class);


	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		CommonResponse response = new CommonResponse();
		LOGGER.error("There is exception happening",e);
		if(e instanceof BusinessException){
			response.setResponseCode(((BusinessException) e).getErrorCode());
			response.setResponseMessage(e.getMessage());
			
		}else if (e instanceof MethodArgumentNotValidException){
			response.setResponseCode(CollectManageResponseCode.RC_PARAMETER_ERROR.getResponseCode());
			response.setResponseMessage(CollectManageResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
			
		} else{
			response.setResponseCode(CollectManageResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
			if(StringUtil.isNotBlank(e.getMessage())){
				response.setResponseMessage(e.getMessage());
			}else{
				response.setResponseMessage(CollectManageResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
			}
		}
		return response;
	}
}
